package com.five.controller;

import com.alibaba.fastjson.JSON;
import com.five.entity.*;
import com.five.service.*;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/2/27.
 */
@RestController
@RequestMapping("/youxue")
public class TravelController {

    private static final Logger looger = Logger.getLogger(TravelController.class);

    @Autowired
    private TravelService travelService;
    @Autowired
    private FileGroupService fileGroupService;
    @Autowired
    private FileService fileService;
    @Autowired
    private TravelCommentService travelCommentService;
    @Autowired
    private UserService userService;
    @Autowired
    private HttpServletRequest request;


    /**
     * 发布游记
     * @param description
     * @param file
     * @return
     */
    @RequestMapping(value = "/publishTravel",method = RequestMethod.POST)
    public String publishTravel(@RequestParam("description") String description,
                                @RequestParam("file") MultipartFile file[],
                                @RequestParam("userId") String id){

        looger.info("file-size:"+file.length);

//        User currentUser =
//                (User) request.getSession().getAttribute("userLogin");

        Integer userId = Integer.valueOf(id);

        FileGroup fileGroup = new FileGroup();
        fileGroup.setGroupName("游记");
        fileGroupService.addFileGroup(fileGroup);

        Travel travel = new Travel();
        travel.setUserId(userId);
        travel.setDescription(description);
        travel.setTravelFileGroupId(fileGroup.getId());
        travelService.addTravel(travel);

        String savePath = "F:\\AllJavaWeb\\YouXue1\\src\\main\\webapp\\upload";

        String newFileName = null;
        String filePath = null;
        long size = 0;
        String suffixName = null;
        if (file != null) {
            for (MultipartFile file1 : file) {

                //获取文件名称
                String fileName = file1.getOriginalFilename();
                //获取后缀名
                suffixName = fileName.substring(fileName.indexOf(".") + 1);
                //图片大小
                size = file1.getSize();
                //新文件名称
                newFileName = System.currentTimeMillis() + "." + suffixName;
                //新文件路劲
                filePath = savePath + "\\" + newFileName;
                //获取存储文件路径
                java.io.File fileDir = new java.io.File(savePath);
                if (!fileDir.exists()) {
                    //如果文件夹没有：新建
                    fileDir.mkdirs();
                }
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(filePath);
                    fos.write(file1.getBytes());
                    fos.flush();
                } catch (Exception e) {
                    e.printStackTrace();

                } finally {
                    try {
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();

                    }
                }

                File file2 = new File();
                file2.setFileGroupId(fileGroup.getId());
                file2.setFileRealName("upload" + "/" + newFileName);
                file2.setFileSize(size);
                fileService.addFile(file2);
            }
            return "{\"result\":\"true\",\"msg\":\"success\"}";
        }else {
            return "{\"result\":\"true\",\"msg\":\"file is null\"}";
        }

    }

    /**
     * 根据游记发布评论
     * @param id
     * @param description
     */
    @RequestMapping(value = "/addTravelComment",method = RequestMethod.GET)
    public void addTravelComment(@RequestParam("travelId") Integer id,
                                 @RequestParam("description") String description){
        User currentUser =
                (User) request.getSession().getAttribute("userLogin");
        TravelComments travelComments = new TravelComments();
        travelComments.setUserId(currentUser.getUserId());
        travelComments.setDescription(description);
        travelCommentService.addTravelComment(travelComments);

        Travel travel = travelService.selectByPrimaryKey(id);
        if (travel.getTravelCommentsIds() == null){
            travel.setTravelCommentsIds(String.valueOf(travelComments.getId()));
        }else {
            String ids = travel.getTravelCommentsIds()+","+travelComments.getId();
            travel.setTravelCommentsIds(ids);
        }
        travel.setId(travel.getId());
        travelService.updateCommentsId(travel);
    }

    /**
     * 用户的个人游记
     * @return
     */
    @RequestMapping(value = "/showOneTravel",method = RequestMethod.GET,produces ="text/plain;charset=UTF-8" )
    public String showOneTravel(){
        User currentUser =
                (User) request.getSession().getAttribute("userLogin");
        List<Map<String,Object>> mapList = new ArrayList<Map<String, Object>>();
        Map<String,Object> map;
        List<Travel> travels = null;
        try {
            travels = travelService.selectByUserId(currentUser.getUserId());
        }catch (Exception e){
            looger.info("0:"+e.getMessage());
            return "";
        }
        for (Travel travel:travels) {
            map = new HashMap<String,Object>();
            map.put("currentUser-userAvatar",currentUser.getUserAvatar());
            map.put("currentUser-nickname",currentUser.getNickname());
            map.put("travel",travel);

            List<File> files = null;
            try {
                files = fileService.selectFiles(travel.getTravelFileGroupId());
                map.put("file",files);
            }catch (Exception e){
                map.put("file","");
                looger.info("1:"+e.getMessage());
            }


            String[] strs;
            try {
                strs = travel.getTravelCommentsIds().split(",");
                List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
                Map<String,Object> map1 = null;
                for (int i = 0; i < strs.length; i++) {
                    int travelCommentId = Integer.parseInt(strs[i]);
                    TravelComments travelComments = travelCommentService.selectByPrimaryKey(travelCommentId);
                    map1.put("travelComment",travelComments);
                    User user = userService.getUserById(travelComments.getUserId());
                    map1.put("comment-userAvatar",user.getUserAvatar());
                    map1.put("comment-nickname",user.getNickname());
                    list.add(map1);
                }
                map.put("travelComments",list);
            }catch (Exception e){
                map.put("travelComments","");
            }
            mapList.add(map);
        }
        return JSON.toJSON(mapList).toString();
    }

    /**
     * 所有的游记
     * @return
     */
    @RequestMapping(value = "/showAllTravel",method = RequestMethod.GET,produces ="text/plain;charset=UTF-8")
    public String showAllTravel(){

        List<Map<String,Object>> mapList = new ArrayList<Map<String, Object>>();
        Map<String,Object> map;

        List<Travel> travelList = null;
        try {
            travelList = travelService.selectAll();
        }catch (Exception e){
            looger.info("0:"+e.getMessage());
            return "";
        }

        for (Travel travel:travelList) {
            looger.info(travel.toString());
            User user = userService.getUserById(travel.getUserId());
            map = new HashMap<String,Object>();
            map.put("TravelUser-userAvatar",user.getUserAvatar());
            map.put("TravelUser-nickname",user.getNickname());
            map.put("travel",travel);

            List<File> files = null;
            try {
                files = fileService.selectFiles(travel.getTravelFileGroupId());
                map.put("file",files);
            }catch (Exception e){
                map.put("file","");
                looger.info("1:"+e.getMessage());
            }

            String[] strs;
            try {
                strs = travel.getTravelCommentsIds().split(",");
                List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
                Map<String,Object> map1 = null;
                for (int i = 0; i < strs.length; i++) {
                    int travelCommentId = Integer.parseInt(strs[i]);
                    TravelComments travelComments = travelCommentService.selectByPrimaryKey(travelCommentId);
                    map1.put("travelComment",travelComments);
                    User user1 = userService.getUserById(travelComments.getUserId());
                    map1.put("comment-userAvatar",user1.getUserAvatar());
                    map1.put("comment-nickname",user1.getNickname());
                    list.add(map1);
                }
                map.put("travelComments",list);
            }catch (Exception e){
                map.put("travelComments","");
            }
            mapList.add(map);

        }

        return JSON.toJSON(mapList).toString();
    }

}
